package it.elis.media.library.security;

import java.util.List;
import java.util.Vector;

import it.elis.media.library.model.data.Role;
import it.elis.media.library.model.data.User;
import it.elis.media.library.service.SecurityService;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.GrantedAuthority;

public class ElisAuthenticationProvider  implements AuthenticationProvider {

	Logger logger = Logger.getLogger(this.getClass());
	
	@Autowired
	SecurityService securityService;
	
	@Override
	public Authentication authenticate(Authentication authentication)
			throws AuthenticationException {
		logger.debug("autenticazione");
		String username = authentication.getName();
		String password = (String) authentication.getCredentials();
		logger.debug("username: " + username);
		logger.debug("password: " + password);
		try {
			
			User user = securityService.login(username, password);
			// carico l'utente
			List<GrantedAuthority> authorities = new Vector<GrantedAuthority>();
			// carico tutti i suoi ruoli
			for (Role role : securityService.getRoles(username)) {
				authorities.add(new RoleAuthority(role.getCodeRole()));
			}
			return new UsernamePasswordAuthenticationToken(user.getUserName(), user.getPassword(), authorities);
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new BadCredentialsException(e.getMessage());
		}
	}

	@Override
	public boolean supports(Class<?> arg0) {
		return true;
	}

}
